var modifyOrAddFlag;

$(document).ready(function(){
		$('#win').window('close');

		//导入
		$('#import_link').window({
			width:465,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false,
			shadow:false
		});
		$('#import_link').window('close');  //关闭窗口
		
		$(".button_con a" ).removeClass("l-btn-plain");

		$("#selFileBtn").click(function(e){
			e.preventDefault();
			//$("#file").click();
		});
		
		$(".import_con").delegate("#importLinkFile" ,"change", function() {
		    $("#fileName").val($('#importLinkFile').val());
		    //clearAutofillStyle();
		});
		
		//所属领域下拉框
		$('#comboxSearchfieldName').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable: false,
		    method:'get',
		    loadFilter: function(data){
		    	var allCheck = {'id':'','name':'全部'};
		    	data.content.unshift(allCheck);
		    	return data.content;
		    },
		    onSelect: function(record){
				
				if(record.id !== '')
				{
					comboxSearchSystemName.combobox({
					  disabled: false,
					  method:'get',
					  queryParams: {fieldId: record.id},
					  url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
					  valueField: 'id',
					  textField: 'name',
					  data:'',
					loadFilter: function(data){
						var allCheck = {'id':'','name':'全部'};
						data.content.unshift(allCheck);
						return data.content;
					},
					onLoadSuccess:function(){
						comboxSearchSystemName.combobox('setValue','');
					}
				  }).load();
				}else
				{
					comboxSearchSystemName.combobox({
					  disabled: true,
					  editable: false				  
					});
				}
		    },
		    onLoadSuccess:function(){
		    	$('#comboxSearchSystemName').combobox('setValue','');
		    }
		});
		
		//所属系统下拉框
		var comboxSearchSystemName = $('#comboxSearchSystemName').combobox({
          disabled: true,
          valueField: 'id',
          textField: 'name',
          editable: false,
		  data:[{id:'',name:'全部','selected':'true'}]
      });
	  
	  
	  $('#comboxFieldName').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	var allCheck = {'id':'','name':'请选择'};
		    	data.content.unshift(allCheck);
		    	return data.content;
		    },
		    onSelect: function(record){
				if(record.name !== "请选择")
				{
					$("#comboxFieldNameHidden").attr("data-hasVal","true").val(record.name);
					$("#comboxSystemNameHidden").attr("data-hasVal","false").val("");
				}else
				{
					$("#comboxFieldNameHidden").attr("data-hasVal","false").val("");
				}
		    	comboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
					data:'',
        		    loadFilter: function(data){
        		    	var allCheck = {'id':'','name':'请选择'};
        		    	data.content.unshift(allCheck);
        		    	return data.content;
        		    },
					onSelect: function(record){
						if(record.name !== "请选择")
						{
							$("#comboxSystemNameHidden").attr("data-hasVal","true").val(record.name);
						}else
						{
							$("#comboxSystemNameHidden").attr("data-hasVal","false").val("");
						}
					}
                }).load();
		    }
		    
		});
		
		
		var comboxSystemName = $('#comboxSystemName').combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false,
			url:'',
			data:[],
			loadFilter:function(data){
				var allCheck = {id:'',name:'请选择','selected':'true'};
				data.unshift(allCheck);
				return data;
			}
		  	
        });
	  
	  
	  	$('#comboxImportFieldName').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	var allCheck = {'id':'','name':'请选择'};
		    	data.content.unshift(allCheck);
		    	return data.content;
		    },
		    onSelect: function(record){
				if(record.name !== "请选择")
				{
					$("#comboxImportFieldNameHidden").attr("data-hasVal","true").val(record.name);
					$("#comboxImportSystemNameHidden").attr("data-hasVal","false").val("");
				}else
				{
					$("#comboxImportFieldNameHidden").attr("data-hasVal","false").val("");
				}
		    	comboxImportSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
					data:'',
        		    loadFilter: function(data){
        		    	var allCheck = {'id':'','name':'请选择'};
        		    	data.content.unshift(allCheck);
        		    	return data.content;
        		    },
					onSelect: function(record){
						if(record.name !== "请选择")
						{
							$("#comboxImportSystemNameHidden").attr("data-hasVal","true").val(record.name);
						}else
						{
							$("#comboxImportSystemNameHidden").attr("data-hasVal","false").val("");
						}
					}
                }).load();
		    }
		    
		});
		
		
		var comboxImportSystemName = $('#comboxImportSystemName').combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false,
			url:'',
			data:[],
			loadFilter:function(data){
				var allCheck = {id:'',name:'请选择','selected':'true'};
				data.unshift(allCheck);
				return data;
			}
		  	
        });
		
		
		$("input[name=import_radio]").change(function(e) {
			
            if($(this).val() === "1")
			{
				$(".database").css("display","block");
				$(".template").css("display","none"); 				

			}else
			{
				$(".database").css("display","none");
				$(".template").css("display","block"); 
				
			}
        });
		
		
	  
		$("input[name=radioDatabaseInstance]").change(function(e) {
			
            if($(this).val() === "1")
			{
				$('#txtServiceName').validatebox({ required: false });
				$("#host, #port, #serviceName").validatebox({ required: true });
				$(".serviceName_li").css("display","none");
				$(".tns_li").css("display","block");
				

			}else
			{
				$('#txtServiceName').validatebox({ required: true });
				$("#host, #port, #serviceName").validatebox({ required: false });
				$(".serviceName_li").css("display","block");
				$(".tns_li").css("display","none");
				
			}
        });
		

		var b = $("#port");
		var c = $("#host");//host
		var d = $("#serviceName");//servicename
		var e = $("#txtServiceName");//服务实例名
		
		$('#tnsnames').click(function(){
			if($(this).is(':checked'))
			{
				b.attr("disabled","disabled");
				c.attr("disabled","disabled");
				d.attr("disabled","disabled");
				e.removeAttr("disabled");

			}
		});

		$('#publics').click(function(){
			var a= document.getElementById('publics');
			var g= $("#txtUser");
			if(a.checked){
				$("#txtUser").val("PUBLIC");
				g.attr("disabled","disabled").removeClass("validatebox-invalid");
				
			}else{
				$("#txtUser").val("");
				g.removeAttr("disabled");
			}
			
		});
		
		$('#nothing').click(function(){
			if($(this).is(':checked'))
			{
				b.removeAttr("disabled");
				c.removeAttr("disabled");
				d.removeAttr("disabled");
			}
		});
		
		
		//提示例子
		$('#tips_img').window({
			width:465,
			height:415,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false
		});
		$('#tips_img').window('close');  //关闭窗口
		$('#tips_img_open').click(function(e) {
            $('#tips_img').window('open'); 
        });
		
		//预览SQL
		$('#tips_sql').window({
			width:465,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false
		});
		$('#tips_sql').window('close');  //关闭窗口
		$('.tips_sql_cal').click(function(e) {
            $('#tips_sql').window('close');
        });
		var urlParamObj = getParamobjFromUrl();
		var name = urlParamObj.name;
		$('#txtSearchDbLink').val(name);
		
		//执行接口服务设置表格
		$("#datagrid").datagrid({
			url : BASE_URL_DBLINK_MANAGE_SEARCH +'/findByExample' + '?v=' + Math.random(),
			method:'get',
			autoRowHeight:true,
			nowrap:false,
			pageSize:20,
			singleSelect:true,
			striped:true,
			pageList:[10,20,50,100],
			columns:[[
						{field:'',width:10,checkbox:true},
						{field:'fieldName',title:'领域',width:70},
						{field:'fieldSystemName',title:'系统',width:70},
						{field:'ownerHost',title:'源主机',width:100},
						{field:'ownerServiceName',title:'源数据库实例名',width:95,align:'left'},
						{field:'name',title:'DBLINK链接名',width:95,align:'left'},
						{field:'ownerUser',title:'所属用户',width:80,align:'left'},
						{field:'host',title:'目标主机',width:100},
						{field:'servicePort',title:'目标库端口',width:70},
						{field:'destUserCode',title:'目标库账号',width:80,align:'left'},
						{field:'serviceName',title:'服务实例名',width:80,align:'left'},
						{field:'wqe',title:'操作',width:80,
							formatter: function(value,row,index){
							return '<a href="javascript:void(0);" class="default_btn" onclick="SQL(' + index + ')">' + '生成SQL' +'</a>';		
					} 
						
						}
			      ]],
			pagination:true,
			onSelect:function(rowIndex,rowData){
				$("#toolbar_edit").linkbutton('enable');
				$("#toolbar_delete").linkbutton('enable');
			},
			loadFilter:function(data){
				return {
					total: data.totalElements,
					rows: data.content
				};
			},
			//条件查询
			onBeforeLoad:function(param){
				//$(".datagrid-header-check").text('');
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;
				
				param.sort = 'createTime,desc';
				var fieldName = $('#comboxSearchfieldName').combobox('getValue');
				if(fieldName != ""){
					param.fieldName = fieldName;
				}
				
				var fieldSystemName = $('#comboxSearchSystemName').combobox('getValue');
				if(fieldSystemName != ""){
					param.fieldSystemName = fieldSystemName;
				}
				var name = $('#txtSearchDbLink').val();
				if(name!=""){
					param.name=name;
				}
				var host =$('#txtSearchHost').val();
				if(host!=""){
					param.host=host;
				}
				var ownerHost = $('#txtSearchOwnerHost').val();
				if(ownerHost!=""){
					param.ownerHost=ownerHost;
				}
				var ownerServiceName = $('#txtSearchOwnerServiceName').val();
				if(ownerServiceName!=""){
					param.ownerServiceName=ownerServiceName;
				}
				param.v = (new Date().getTime()) ^ Math.random()
				
			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 
		
		
		//数据库导入
		var requestOracle;
		var loading_point = {
				timer:null,
				len:3,
				count:0
			};
		function loading()
		{
		 	if(loading_point.count < loading_point.len)
			{
				loading_point.count++;
				$("#progressbar_point").text($("#progressbar_point").text() + ".");
			}else
			{
				loading_point.count = 0;
				$("#progressbar_point").text("");
			}	
		}
		$("#importDatabaseBtn").click(function(e) {
			var importDatabaseAddress = $("#importDatabaseAddress").val();
			var importPort = $("#importPort").val();
			var importDatabase = $("#importDatabase").val();
			var importUser = $("#importUser").val();
			var importPass = $("#importPass").val();
			var importFieldSystem = $('#comboxImportSystemName').combobox('getText');
			var jsonData = {onwerHost:importDatabaseAddress, ownerPort : importPort,onwerServiceName : importDatabase,fieldSystem : importFieldSystem,userCode : importUser, password : importPass};
		
		var jsonStr = JSON.stringify(jsonData);
			if($("#importForm").form("validate"))
			{
				$("#importDatabaseBtn").linkbutton("disable");
				$("#importDatabaseBtn .l-btn-text").text("读取中...");
				$("#progressbar, #progressbar_tips").fadeIn();
				loading_point.timer = setInterval(loading,200);
				requestOracle = $.ajax({
						url:BASE_URL_ORACLE+ '/link/oracle' + '?v=' + Math.random(),
						dataType:'json',
						type:'post',
						contentType:"application/json",
						data: jsonStr,
						success:function(data){
							if(data.resultCode === "SUCCESS")
							{
								$("#progressbar, #progressbar_tips").fadeOut();
								$.messager.alert('提示', '<p>导入成功！</p>','info');
								$("#datagrid").datagrid("reload", BASE_URL_DBLINK_MANAGE_SEARCH +'/findByExample' + '?v=' + Math.random());
								$('#import_link').window('close'); 
								$("#importDatabaseBtn").linkbutton("enable");
								$("#importDatabaseBtn .l-btn-text").text("读取");
								requestOracle = null;
								clearInterval(loading_point.timer);
							}
							else if(data.resultCode === "TIMEOUT")
							{
								$("#progressbar, #progressbar_tips").fadeOut();
								$.messager.alert('错误', '<p>导入超时，请重新导入表单！</p>','error');
								$("#importDatabaseBtn").linkbutton("enable");
								$("#importDatabaseBtn .l-btn-text").text("读取");
								requestOracle = null;
								clearInterval(loading_point.timer);
							}else if(data.resultCode === "FALSE")
							{
								$("#progressbar, #progressbar_tips").fadeOut();
								$.messager.alert('错误', '<p>请检查你输入的信息是否正确！</p>','error');
								$("#importDatabaseBtn").linkbutton("enable");
								$("#importDatabaseBtn .l-btn-text").text("读取");
								requestOracle = null;
								clearInterval(loading_point.timer);
							}else if(data.resultCode === "NULL")
							{
								$("#progressbar, #progressbar_tips").fadeOut();
								$.messager.alert('错误', '<p>目标数据库实例中不存在DBlink！</p>','error');
								$("#importDatabaseBtn").linkbutton("enable");
								$("#importDatabaseBtn .l-btn-text").text("读取");
								requestOracle = null;
								clearInterval(loading_point.timer);
							}
						}
				});
			}
        });

	
		$("#import_link").siblings(".panel-header").children(".panel-tool").children(".panel-tool-close").click(function(e) {
			if(requestOracle) 
			{
				requestOracle.abort();
				$.messager.alert('警告', '<p>表单停止读取，需要读取请重新导入！</p>','warning');
				$("#progressbar, #progressbar_tips").fadeOut();
				$("#importDatabaseBtn").linkbutton("enable");
				$("#importDatabaseBtn .l-btn-text").text("读取");
				clearInterval(loading_point.timer);
				requestOracle = null;
			}
        });	
});		
	
	comboValidate("#comboxFieldName","所属领域");
	comboValidate("#comboxSystemName","系统名称");
	
	comboValidate("#comboxImportFieldName","领域");
	comboValidate("#comboxImportSystemName","系统");
	function onCheckSave(){
		var row = $('#datagrid').datagrid('getSelected');
		var name = $("#txtDBLINKLinkName").val();
		var ownerHost = $("#txtDatabaseAddress").val();
		var ownerPort = $("#txtPort").val();
		var ownerUser = $("#txtUser").val();
		var ownerServiceName = $("#txtOwnerServiceName").val();
		var destUser = $("#txtTargetDatabaseAccount").val();
		var destUserPassWord = RSAUtils.encryptedString(key,$("#txtTargetPassword").val());
		
		var fieldSystemId = $("#comboxSystemName").combobox('getValue');
		
		if($('input[name=radioDatabaseInstance]:checked').val() === "1") {
			var serviceName = $("#serviceName").val();
			var port = $("#port").val();
			var host = $("#host").val();
		}else
		{
			var serviceName = $("#txtServiceName").val();
		}
		
		var jsonData = {
						id : '0',
						fieldSystemName:fieldSystemId,
						name : name,
						ownerHost : ownerHost,
						ownerPort : ownerPort,
						ownerUser : ownerUser,
						ownerServiceName : ownerServiceName,
						destUser : destUser,
						destUserPassWord : destUserPassWord,
						host : host,
						port : port,
						serviceName : serviceName};
		
		
		
		if($("#addForm").form("validate")){
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
			if(!modifyOrAddFlag){
				var checkParam = {name:$("#txtDBLINKLinkName").val(), ownerHost:$("#txtDatabaseAddress").val(),originalId:row.id};
				$.ajax({
					url:BASE_URL_DBLINK_MANAGE_CRUD +'/search/checkIsCanSave' + '?v=' + Math.random(),
					dataType:'json',
					type:'get',
					contentType:"application/json",
					data: checkParam,
					success:function(data){
						if(!data.isCanSave){
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
							$.messager.alert('提示','<p>数据库中存在相同源数据库地址的DBlink链接名,请重新命名</p>','info');
						}else{
							jsonData.id = row.id;
							var jsonStr = JSON.stringify(jsonData);
							$.ajax({
								url:BASE_URL_DBLINK_MANAGE_CRUD + '/saveOrUpdate',
								dataType:'json',
								type:'post',
								contentType:"application/json",
								data: jsonStr,
								success:function(){
									$.messager.alert('提示','<p>修改成功!</p>','info');
									$("#datagrid").datagrid("reload", BASE_URL_DBLINK_MANAGE_SEARCH + '/findByExample' + '?v=' + Math.random());
									$('#win').window('close');
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
								},
								error:function(xhr,s,err){
									$.messager.alert("错误","<p>服务异常，修改DBLink信息失败，请重新登录或稍后再试！</p>","error");	
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
								}
							});
						}
					},
					error:function(){
						$.messager.alert("错误","<p>服务异常，修改DBLink信息失败，请重新登录或稍后再试！</p>","error");		
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
	 				}
				});
			}else{
				var checkParam = {name:$("#txtDBLINKLinkName").val(), ownerHost:$("#txtDatabaseAddress").val()};
				$.ajax({
					url:BASE_URL_DBLINK_MANAGE_CRUD +'/search/checkIsCanSave' + '?v=' + Math.random(),
					dataType:'json',
					type:'get',
					contentType:"application/json",
					data: checkParam,
					success:function(data){
						if(!data.isCanSave){
							$.messager.alert('警告','<p>数据库中存在相同数据库地址的DBlink链接名,请重新命名!</p>','warning');
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
						}else{
							var jsonStr = JSON.stringify(jsonData);
							$.ajax({
								url: BASE_URL_DBLINK_MANAGE + '/saveOrUpdate',
								type:'post',
								contentType:"application/json",
								data: jsonStr,
								timeout:30000,
								success:function(){
									$.messager.alert('提示','<p>新增成功!</p>','info');
									$('#win').window('close');
									$("#datagrid").datagrid("reload", BASE_URL_DBLINK_MANAGE_SEARCH + '/findByExample' + '?v=' + Math.random());
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
								},
								error:function(xhr,s,err){
									$.messager.alert("错误","<p>服务异常，新增DBLink失败，请重新登录或稍后再试！</p>","error");	
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
								}
							});
						}
					},
					error:function(){
						$.messager.alert("错误","<p>服务异常，新增DBLink失败，请重新登录或稍后再试！</p>","error");		
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
	 				}
				});
			}
		}
	}
	
	
	function SQL(index){
		$('#datagrid').datagrid('selectRow',index);
		var row = $('#datagrid').datagrid('getSelected');
		var ownerUserPub = row.ownerUser.toUpperCase();
		if(ownerUserPub == "PUBLIC")
		{
			$("#tips_sql .public").css("display","inline");
		}else
		{
			$("#tips_sql .public").css("display","none");
		}
		if(row.host !=""){
			$(".DBLINKLinkName").html(row.name);
			$("#targetDatabaseAccount").html(row.destUserCode);
			$("#targetPassword").html("*****");
			$("#serviceNameSql").html(row.serviceName);
			$("#hostVal").html(row.host);
			$("#portVal").html(row.servicePort);
			$("#serviceNameVal").html(row.serviceName);
			$(".using").css("display","none");
			$(".tns").css("display","block");
			$('#tips_sql').window('open'); 
		}else{
			$(".DBLINKLinkName").html(row.name);
			$("#targetDatabaseAccount").html(row.destUserCode);
			$("#targetPassword").html(row.destPassword);
			$("#serviceNameSql").html(row.serviceName);
			$(".tns").css("display","none");
			$(".using").css("display","block");
			$('#tips_sql').window('open'); 
		}
		
		
	}
	//SQL预览
	function previewSQL() {
		
		if($("#txtDBLINKLinkName").val()=="")
		{
			$.messager.alert('警告','<p>请输DBLink链接名信息！</p>','warning');
			return;
		}else if($("#txtTargetDatabaseAccount").val()=="")
		{
			$.messager.alert('警告','<p>请输入目标库帐号信息！</p>','warning');
			return;
		}else if($("#txtTargetPassword").val()=="")
		{
			$.messager.alert('警告','<p>请输入目标库密码信息！</p>','warning');
			return;
		}else{
			$(".DBLINKLinkName").html($("#txtDBLINKLinkName").val());
			$("#targetDatabaseAccount").html($("#txtTargetDatabaseAccount").val());
			$("#targetPassword").html("*****");
			$("#serviceNameSql").html($("#txtServiceName").val());
			$("input[name=radioDatabaseInstance]").each(function(index, element) {
			   if($(this).is(':checked'))
			   {
					if($("#txtUser").attr("disabled"))
					{
						$(".public").css("display","inline");
					}else
					{
						$(".public").css("display","none");
					}
				   if($(this).val() == "1")
				   {
					   if($("#host").val() == "")
					   {
						  $.messager.alert('警告','<p>请输入完整的HOST信息！</p>','warning'); 
						  return false;
					   }else if($("#port").val() == "")
					   {
						  $.messager.alert('警告','<p>请输入完整的PORT信息！</p>','warning'); 
						  return false; 
					   }else if($("#serviceName").val() == "")
					   {
						  $.messager.alert('警告','<p>请输入完整的SERVICE_NAME信息！</p>','warning'); 
						  return false; 
					   }
					   else
					   {
						$("#hostVal").html($("#host").val());
						$("#portVal").html($("#port").val());
						$("#serviceNameVal").html($("#serviceName").val());
						$(".using").css("display","none");
						$(".tns").css("display","block");
						$('#tips_sql').window('open'); 
					   }
					}else
					{
						if($("#txtServiceName").val()=="")
					   {
						  $.messager.alert('警告','<p>请输入服务实例名信息！</p>','warning'); 
						  return false;
					   }else
					   {
						$(".tns").css("display","none");
						$(".using").css("display","block");
						$("#host, #port, #serviceName").val('');
						$('#tips_sql').window('open'); 
					   }
					}
			   }
			});
			
		}
	}
	//复制
	$(".saveSql").click(function(e) {
        copyToClipboard($("#sqlTxt").text());
    });
	//点击文本框复制其内容到剪贴板上方法
	function copyToClipboard(txt) {
		if (window.clipboardData) {
			window.clipboardData.clearData();
			window.clipboardData.setData("Text", txt);
			$.messager.alert('提示','<p>已经成功复制到剪帖板上!</p>','info');
		} else if (navigator.userAgent.indexOf("Opera") != -1) {
			window.location = txt;
		} else if (window.netscape) {
			try {
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			} catch (e) {
				$.messager.alert('提示','<p>被浏览器拒绝！\n请在浏览器地址栏输入"about:config"并回车\n然后将"signed.applets.codebase_principal_support"设置为"true"!</p>','info');
			}
			var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
			if (!clip) return;
			var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
			if (!trans) return;
			trans.addDataFlavor('text/unicode');
			var str = new Object();
			var len = new Object();
			var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
			var copytext = txt;
			str.data = copytext;
			trans.setTransferData("text/unicode", str, copytext.length * 2);
			var clipid = Components.interfaces.nsIClipboard;
			if (!clip) return false;
			clip.setData(trans, null, clipid.kGlobalClipboard);
			$.messager.alert("提示","<p>已经成功复制到剪帖板上！</p>","info");
		}else
		{
			$.messager.alert("提示","<p>您的复制操作被浏览器拒绝，请手动复制！</p>","info");
		}
	}
	//进入新增界面	
	function add(){
		$("#win").window('setTitle','DBLINK管理-新增');
		modifyOrAddFlag = true;
		$('#addForm')[0].reset();
		$("#txtUser").removeAttr("disabled");		
		$("#txtServiceName").attr("disabled","disabled");	
		$("#port").removeAttr("disabled");
		$("#host").removeAttr("disabled");
		$("#serviceName").removeAttr("disabled");	
		$(".serviceName_li").css("display","none");
		$(".tns_li").css("display","block");
		$('#win').window('open');
		$("body").css("overflow-x","hidden");
		$('#txtServiceName').validatebox({ required: false });
		$("#host, #port, #serviceName").validatebox({ required: true });
		var data = $('#comboxFieldName').combobox('getData');	
		$("#comboxFieldName").combobox('setValue',data[0].id);
		
		setTimeout(function(){
			$("#comboxFieldName").siblings(".textbox").children(".textbox-text").val($("#comboxFieldName").combobox('getText'));
			$('#comboxSystemName').combobox({
				disabled: true,
				valueField: 'id',
				textField: 'name',
				editable:false,
				url:'',
				data:[],
				loadFilter:function(data){
					var allCheck = {id:'',name:'请选择','selected':'true'};
					data.unshift(allCheck);
					return data;
				}
			});
		},50);
		$("#comboxFieldNameHidden").attr("data-hasVal","false").val('');
		$("#comboxSystemNameHidden").attr("data-hasVal","false").val('');
	}
	//进入修改界面
	function update(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert("警告","<p>请选中要修改的记录!</p>","warning");
		}else{
			modifyOrAddFlag = false;
			$("#txtDBLINKLinkName").val(row.name);
			$("#txtDatabaseAddress").val(row.ownerHost);
						
			$("#txtPort").val(row.ownerPort);
			$("#txtUser").val(row.ownerUser);
			$("#txtOwnerServiceName").val(row.ownerServiceName);
			$("#txtTargetDatabaseAccount").val(row.destUserCode);
			$("#txtTargetPassword").val(row.destPassword);
			$("#comboxFieldName").combobox('setValue',row.fieldId);
			
			$('#comboxSystemName').combobox({
				disabled: false,
				method:'get',
				queryParams: {fieldId: row.fieldId},
				url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
				valueField: 'id',
				textField: 'name',
				data:'',
				loadFilter: function(data){
					var allCheck = {'id':'','name':'请选择'};
					data.content.unshift(allCheck);
					return data.content;
				},
				onSelect: function(record){
					if(record.name !== "请选择")
					{
						$("#comboxSystemNameHidden").attr("data-hasVal","true").val(record.name);
					}else
					{
						$("#comboxSystemNameHidden").attr("data-hasVal","false").val("");
					}
				}
			}).load();
			$("#comboxSystemName").combobox('setValue',row.fieldSystemId);
			$("#comboxFieldNameHidden").attr("data-hasVal","true").val(row.fieldId);
			$("#comboxSystemNameHidden").attr("data-hasVal","true").val(row.fieldSystemId);
			
			
			if($("#txtUser").val()=="PUBLIC"){
				$("#txtUser").attr("disabled","disabled").removeClass("validatebox-invalid");
				$("#publics")[0].checked = true;
			}else{
				$("#txtUser").removeAttr("disabled");
				$("#publics")[0].checked=false;
			}
			var b = $("#port");//port
			var c = $("#host");//host
			var d = $("#serviceName");//servicename
			var e = $("#txtServiceName");//服务实例名
			var f = $("#txtUser");
			
			if(row.host != null&&row.servicePort != null){
				$("#serviceName").val(row.serviceName);
				$('#txtServiceName').val('');
				$('#txtServiceName').validatebox({ required: false });
				$("#host, #port, #serviceName").validatebox({ required: true });
				e.attr("disabled","disabled");
				c.removeAttr("disabled");
				b.removeAttr("disabled");
				d.removeAttr("disabled");
				$("#host").val(row.host);
				$("#nothing")[0].checked = true;
				$(".serviceName_li").css("display","none");
				$(".tns_li").css("display","block");
			}else{
				$("#txtServiceName").val(row.serviceName);
				$("#host, #serviceName").val('');
				$('#txtServiceName').validatebox({ required: true });
				$("#host, #port, #serviceName").validatebox({ required: false });
				e.removeAttr("disabled");
				c.attr("disabled","disabled");
				b.attr("disabled","disabled");
				d.attr("disabled","disabled");
				$("#txtServiceName").val(row.serviceName);
				$("#tnsnames")[0].checked = true;
				$(".serviceName_li").css("display","block");
				$(".tns_li").css("display","none");
			}
			
			
			
			$("#win").window('setTitle','DBLINK管理-修改');
			$('#win').window('open');
		}
	}
	
	
	//删除
	function del(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert("警告","<p>请选中要删除的记录!</p>","warning");
		}else{
			if (row){
			$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(result){
				if (!result){
					return;
				}
				var checkParam={id:row.id};
				$.ajax({
					url:BASE_URL_DBLINK_MANAGE_CRUD +'/search/checkIsCanDelete' + '?v=' + Math.random(),
					dataType:'json',
					type:'get',
					contentType:"application/json",
					data: checkParam,
					success:function(data){
						if(!data.isCanDelete){
							$.messager.alert('警告','<p>该dblink被引用,不允许删除</p>','warning');
						}else
							{
								if (result){
							 		$.ajax({
										url:BASE_URL_DBLINK_MANAGE_CRUD + '/' + row.id,
										dataType:'json',
										type:'delete',
										async:false,
										contentType:"application/json",
										timeout:30000,
										success:function(){
											$.messager.alert("提示","<p>删除成功!</p>","info");
											$("#datagrid").datagrid("reload", BASE_URL_DBLINK_MANAGE_SEARCH +'/findByExample' + '?v=' + Math.random());
										},
										error:function(xhr,s,err){
											$.messager.alert("错误","<p>服务异常，删除DBLink失败，请重新登录或稍后再试！</p>","error");	
										}
							 		});
								}
							}
					}
				});
			});
		}
		}
	}
	//进入导入界面
	function import_link()
	{
		$("#importDatabaseAddress, #importPort, #importDatabase, #importUser, #importPass").val("");
		$("#importPort").val("1521");
		$("input#database_radio").prop("checked", true);
		$(".database").css("display","block");
		$(".template").css("display","none");
		var data = $("#comboxImportFieldName").combobox("getData");
		var data1 = $("#comboxImportSystemName").combobox("getData");
 		$("#comboxImportFieldName").combobox("select",data[0].id);
		$("#comboxImportSystemName").combobox("select",data1[0].id);
		$("#comboxImportFieldNameHidden").attr("data-hasVal","false").val("");
		$("#comboxImportSystemNameHidden").attr("data-hasVal","false").val("");
		$('#import_link').window('open'); 
	}
	//导入
	function startImport() {
		if($("#importLinkFile").val() == "")
 		{
 			$.messager.alert("警告", "<p>请选择需要导入的.xls或.xlsx格式的文件!</p>","warning");
 			return;
 		}
 		var tempArr = $("#importLinkFile").val().split(".");
 		var selFileType = tempArr[tempArr.length - 1];
 		if(selFileType != "xls" && selFileType != "xlsx")
 		{
 			$.messager.alert("警告", "<p>选择的文件格式有误，请选择.xls或.xlsx格式的文件!</p>","warning");
 			return;
 		}
 		
 		$("#buttons_inport .easyui-linkbutton").linkbutton("disable");
 		$("#buttons_inport .l-btn-text").text("正在导入...");
 		
		//$("#import_form").submit();
		$.ajaxFileUpload({
	        url: '/api/importData/dblink/fileUpload' + '?v=' + Math.random() + "&name=" + encodeURI($("#fileName").val()), 
	        type: 'post',
	        secureuri: false, //一般设置为false
	        fileElementId: 'importLinkFile', // 上传文件的id、name属性名
	        dataType: 'text', //返回值类型，一般设置为json、application/json
	        //data: {name:""}, //传递参数到服务器
	        success: function(data, status){ 
	        	//var resultObj = eval("[" + data.activeElement.innerText + "]")[0];
	            $("#fileName").val($('#importLinkFile').val());
         		$("#buttons_inport .easyui-linkbutton").linkbutton("enable");
         		$("#buttons_inport .l-btn-text").text("确定导入");
         		
	        	var resultObj = JSON.parse(data.slice(data.indexOf(">") + 1,data.indexOf("</")));
	            if(resultObj.backValue === true)
	            {
	            	$('#import_link').window('close'); 
					$("#datagrid").datagrid("reload", BASE_URL_DBLINK_MANAGE_SEARCH +'/findByExample' + '?v=' + Math.random());
	            	$.messager.alert('提示',"<p>导入成功！</p>","info");
	            }
	            else if(resultObj.backValue === false)
	            {
	            	$.messager.alert('错误',"<p>导入失败!所选文件内容为空或存在异常！</p>","error");
	            }
	            else
	            {
	            	$.messager.alert('错误',"<p>导入失败！" + resultObj.backValue + "</p>", "error"); 
	            }
	        },
	        error: function(data, status, e){ 
	            $("#fileName").val($('#importLinkFile').val());
         		$("#buttons_inport .easyui-linkbutton").linkbutton("enable");
         		$("#buttons_inport .l-btn-text").text("确定导入");
         		

				$.messager.alert("错误","<p>服务异常，导入失败，请重新登录或稍后再试！</p>","error");	
	        }
	    });
	}

	//查询
	function search(){
		$("#datagrid").datagrid("reload", BASE_URL_DBLINK_MANAGE_SEARCH +'/findByExample' + '?v=' + Math.random());
	}
	
	function rePage(){
		$('#win').window('close');
		$("body").css("overflow-x","inherit")
		$("#datagrid").datagrid("reload", BASE_URL_DBLINK_MANAGE_SEARCH +'/findByExample' + '?v=' + Math.random());
	}
	function onchange(){
		
	}